package tienich360.com.lib;

import java.security.MessageDigest;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;

public class KeyHash {
	public static String getKeyHash(Activity activity, String packagename) {
		try {
			PackageInfo info = activity.getPackageManager().getPackageInfo(
					packagename, PackageManager.GET_SIGNATURES);
			String keyhash = "";
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				keyhash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
				keyhash = my_decode(keyhash);
				Log.d("KeyHash:", keyhash);
			}
			return keyhash;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String getKeyHash(Activity activity) {
		try {
			String PACKAGE_NAME = activity.getApplicationContext()
					.getPackageName();
			PackageInfo info = activity.getPackageManager().getPackageInfo(
					PACKAGE_NAME, PackageManager.GET_SIGNATURES);
			String keyhash = "";
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				keyhash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
				keyhash = my_decode(keyhash);
				Log.d("KeyHash:", keyhash);
			}
			return keyhash;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String getKeyHash_No_Encode(Activity activity) {
		try {
			String PACKAGE_NAME = activity.getApplicationContext()
					.getPackageName();
			PackageInfo info = activity.getPackageManager().getPackageInfo(
					PACKAGE_NAME, PackageManager.GET_SIGNATURES);
			String keyhash = "";
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				keyhash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
				Log.d("KeyHash:", keyhash);
			}
			return keyhash;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private static String my_decode(String keyhash) {
		String my_keyhash = "";
		try {
			my_keyhash = keyhash.trim().replace("/", "");
			my_keyhash = my_keyhash.replace("%", "");
			my_keyhash = my_keyhash.replace(" ", "");
			my_keyhash = my_keyhash.replace("+", "");
			my_keyhash = my_keyhash.replace("=", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return my_keyhash;
	}
}
